# -*- coding: utf-8 -*-

import os,sys,re,urllib
from app.gmemsess import Session

def filePath(name):
	return os.path.join(os.path.dirname(__file__), name).replace('\\','/')

sys.path.insert(0,filePath('boto.zip'))
sys.path.insert(1, filePath('json2.5.zip'))
os.environ['BOTO_CONFIG'] = filePath('boto.cfg')

import boto,json
config = boto.config

if not config.has_section('Credentials'):
	config.add_section('Credentials')
if not config.has_section('Boto'):
	config.add_section('Boto')
config.set('Credentials', 'is_secure', 'False')

'''
__id = 'GOOG6TODSQZPSZC3CUAK'
__bucketsCache = {
    __id + '': eval(open('data/bucket.html','r').read()),
    __id + 'twty1988': open('data/twty1988.html').read(),
    __id + 'twty19882': open('data/twty19882.html').read(),
    __id + 'zhixu': open('data/zhixu.html').read(),
}
'''

reload = False
reg = re.compile('^/|/$')
def bucketsCache(method):
	def _bucketsCache(self, path, id, key):
		path = reg.sub('',path)
		session = Session(self)
		caches = session.get('__bucketsCache',{})
		#caches = __bucketsCache
		cache = caches.get(id + path,None)
		if cache != reload and cache is not None:
			return cache
		elif cache != reload:
			#turn check parent
			index = path.find('/',0)
			while index > -1:
				cache = caches.get(id + path[0: index],None)
				if cache is not None:
					return cache
				index += 1
				index = path.find('/',index)

		buckets = method(self, path, **{'id': id, 'key': key})
		caches[id + path] = buckets
		session['__bucketsCache'] = caches
		session.save()
		return buckets
	return _bucketsCache


def aclCache(method):
	def _aclCache(self, path, keys, **kwargs):
		id = kwargs['id']
		cacheId = id + path
		session = Session(self)
		caches = session.get('__aclCache',{}).get(cacheId, {})
		keyAcls = {}
		keys_ = []
		if caches != reload:
			for key in keys:
				acl = caches.get(key)
				if acl is not None: keyAcls[key] = acl
				else: keys_.append(key)
		else:
			caches = {}
			keys_ = keys

		if keys_:
			keyAcls_ = method(self, path, keys_, **kwargs)
			caches.update(keyAcls_)
			keyAcls.update(keyAcls_)
			session['__aclCache'] = {cacheId : caches}
			session.save()
			
		return keyAcls
	return _aclCache

def idAndKey(method):
	def _idAndKey(self, *args, **kwargs):
		session = Session(self)
		id = session.get('gsId')
		key = session.get('gsKey')
		
		config.set('Credentials', 'gs_access_key_id', id)
		config.set('Credentials', 'gs_secret_access_key', key)

		kwargs['id'] = id
		kwargs['key'] = key
		return method(self, *args, **kwargs)
	return _idAndKey


def clearCache(method):
	@idAndKey
	def _clearBucket(self, *args, **kwargs):
		path = args[0] if args else self.param('path')
		id = kwargs['id']
		session = Session(self)
		caches = session.get('__bucketsCache',{})
		caches[id + path] = reload

		aclcaches = session.get('__aclCache',{})
		aclcaches[id + path] = reload
		
		session['__bucketsCache'] = caches
		session['__aclCache'] = aclcaches
		session.save()
		return method(self, path, **kwargs)
	return _clearBucket


def browserCheck(method):
	''' only Chrome Safari Firefox '''

	def _browserCheck(self, *args, **kwargs):
		agent = self.request.environ.get('HTTP_USER_AGENT').lower()

		if agent.find('chrome') < 0 and agent.find('firefox') < 0 and agent.find('safari') < 0:
			return self.write('only  Chrome Firefox Safari')
		return method(self, *args, **kwargs)

	return _browserCheck